﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.PowerPoint;
using Microsoft.Office.Tools;

namespace PSCharts
{
    public class PresentationTaskPane
    {
        CustomTaskPaneCollection mPanes = Globals.ThisAddIn.CustomTaskPanes;
        CustomTaskPane mPane;
        Presentation mPres;
        Application mApp;
        
        public PresentationTaskPane(Presentation presentation, System.Windows.Forms.UserControl control, string title)
        {
            mPane = mPanes.Add(control, title);
            
            mPres = presentation;
            mApp = presentation.Application;
            HookUpEvents();
        }

        void HookUpEvents()
        {
            mApp.WindowActivate += Application_WindowActivate;
            mApp.WindowDeactivate += Application_WindowDeactivate;
            mApp.PresentationClose += Application_PresentationClose;
        }

        void UnHookEvents()
        {
            mApp.WindowActivate -= Application_WindowActivate;
            mApp.WindowDeactivate -= Application_WindowDeactivate;
            mApp.PresentationClose -= Application_PresentationClose;
        }

        void Application_WindowActivate(Presentation Pres, DocumentWindow Wn)
        {
            if (mPres == Pres)
                mPane.Visible = true;
        }

        void Application_WindowDeactivate(Presentation Pres, DocumentWindow Wn)
        {
            if (mPres == Pres)
                mPane.Visible = false;
        }

        void Application_PresentationClose(Presentation Pres)
        {
            if (mPres == Pres)
                Close();
        }

        void Close()
        {
            UnHookEvents();
            mPanes.Remove(mPane);
            mPane.Dispose();
        }
    }
}
